<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import myAxios from '../../../plugins/myAxios'
import { useRouter } from 'vue-router'

// 数据定义
const subjectList = ref([]) // 科目列表
const chapterList = ref([]) // 章节列表
const questionList = ref([]) // 题目列表

// 选择状态
const selectedSubject = ref(null)
const selectedChapter = ref(null)
const questionType = ref(null) // 1-选择题 2-综合题
const questionCategory = ref(null) // 1-普通题 2-真题

// 表格列定义
const columns = [
  { prop: 'title', label: '题目标题' },
  { prop: 'content', label: '题目内容' },
  { 
    prop: 'questionType', 
    label: '题目类型(1-选择题/2-综合题)',
    formatter: (row) => row.questionType === 1 ? '选择题' : '综合题'
  },
  { 
    prop: 'questionCategory', 
    label: '题目分类(1-普通题/2-真题)',
    formatter: (row) => row.questionCategory === 1 ? '普通题' : '真题'
  },
  { prop: 'optionA', label: '选项A' },
  { prop: 'optionB', label: '选项B' },
  { prop: 'optionC', label: '选项C' },
  { prop: 'optionD', label: '选项D' },
  { prop: 'answer', label: '答案' },
  { prop: 'analysis', label: '解析' }
]

// 加载状态
const loading = ref(false)

// 监听科目选择变化
watch(selectedSubject, async (newVal) => {
  if (newVal) {
    await fetchChapterList(newVal)
    selectedChapter.value = null
    questionList.value = []
  } else {
    chapterList.value = []
  }
})

// 获取科目列表
const fetchSubjectList = async () => {
  try {
    loading.value = true
    subjectList.value = await myAxios.get('/teacher/researchInfo/subject/list')
  } catch (error) {
    ElMessage.error('获取科目列表失败：' + error)
  } finally {
    loading.value = false
  }
}

// 获取章节列表
const fetchChapterList = async (subjectId) => {
  try {
    loading.value = true
    chapterList.value = await myAxios.get(`/teacher/researchInfo/chapter/getBySubject/${subjectId}`)
  } catch (error) {
    ElMessage.error('获取章节列表失败：' + error)
  } finally {
    loading.value = false
  }
}

// 获取题目列表
const fetchQuestionList = async () => {
  try {
    loading.value = true
    const params = {
      chapterId: selectedChapter.value,
      questionType: questionType.value,
      questionCategory: questionCategory.value
    }
    questionList.value = await myAxios.get('/teacher/examination/question/list', { params })
  } catch (error) {
    ElMessage.error('获取题目列表失败：' + error)
  } finally {
    loading.value = false
  }
}

// 删除题目
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这道题目吗？', '提示', {
      type: 'warning'
    })
    await myAxios.post(`/teacher/examination/question/delete/${row.id}`)
    ElMessage.success('删除成功')
    await fetchQuestionList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + error)
    }
  }
}

// 编辑题目
const handleEdit = (row) => {
  editFormData.value = { ...row }
  editDialogVisible.value = true
}

// 添加题目
const handleAdd = () => {
  if (!selectedChapter.value) {
    ElMessage.warning('请先选择章节')
    return
  }
  formData.value = {
    title: '',
    content: '',
    optionA: '',
    optionB: '',
    optionC: '',
    optionD: '',
    answer: '',
    analysis: '',
    chapterId: selectedChapter.value,
    questionType: 1, // 默认选择题
    questionCategory: 1 // 默认普通题
  }
  dialogVisible.value = true
}

// 新增查询方法
const handleSearch = async () => {
  if (!selectedChapter.value) {
    ElMessage.warning('请先选择章节')
    return
  }
  await fetchQuestionList()
}

// 页面加载时获取科目列表
onMounted(async () => {
  await fetchSubjectList()
})

const router = useRouter()

// 在 script setup 部分添加新的响应式变量
const dialogVisible = ref(false)
const formData = ref({
  title: '',
  content: '',
  optionA: '',
  optionB: '',
  optionC: '',
  optionD: '',
  answer: '',
  analysis: '',
  chapterId: '',
  questionType: 1,
  questionCategory: 1
})

// 添加保存方法
const handleSave = async () => {
  try {
    loading.value = true
    console.log(formData.value)
    await myAxios.post('/teacher/examination/question/add', formData.value)
    ElMessage.success('添加成功')
    dialogVisible.value = false
    await fetchQuestionList()
  } catch (error) {
    ElMessage.error('添加失败：' + error)
  } finally {
    loading.value = false
  }
}

// 在 script setup 中添加编辑相关的变量
const editDialogVisible = ref(false)
const editFormData = ref({
  id: '',
  title: '',
  content: '',
  optionA: '',
  optionB: '',
  optionC: '',
  optionD: '',
  answer: '',
  analysis: '',
  chapterId: '',
  questionType: 1,
  questionCategory: 1
})

// 添加更新方法
const handleUpdate = async () => {
  try {
    loading.value = true
    await myAxios.post('/teacher/examination/question/update', editFormData.value)
    ElMessage.success('更新成功')
    editDialogVisible.value = false
    await fetchQuestionList()
  } catch (error) {
    ElMessage.error('更新失败：' + error)
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="examination-question-container">
    <!-- 添加新增按钮 -->
    <div class="operation-section">
      <el-button type="primary" @click="handleAdd">新增题目</el-button>
    </div>

    <!-- 顶部选择区域 -->
    <div class="filter-section">
      <el-select v-model="selectedSubject" placeholder="请选择科目">
        <el-option
          v-for="item in subjectList"
          :key="item.id"
          :label="item.subjectName"
          :value="item.id"
        />
      </el-select>

      <el-select
        v-model="selectedChapter"
        placeholder="请选择章节"
        :disabled="!selectedSubject">
        <el-option
          v-for="item in chapterList"
          :key="item.id"
          :label="item.chapterName"
          :value="item.id"
        />
      </el-select>

      <el-button type="primary" @click="handleSearch">查询</el-button>
    </div>

    <!-- 题目列表 -->
    <el-table v-loading="loading" :data="questionList" border>
      <el-table-column
        v-for="col in columns"
        :key="col.prop"
        :prop="col.prop"
        :label="col.label"
        :formatter="col.formatter"
      />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="dialogVisible"
      title="新增题目"
      width="60%">
      <el-form :model="formData" label-width="100px">
        <el-form-item label="题目类型">
          <el-radio-group v-model="formData.questionType">
            <el-radio :value="1" :label="1">选择题</el-radio>
            <el-radio :value="2" :label="2">综合题</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题目分类">
          <el-radio-group v-model="formData.questionCategory">
            <el-radio :value="1" :label="1">普通题</el-radio>
            <el-radio :value="2" :label="2">真题</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题目标题">
          <el-input v-model="formData.title" />
        </el-form-item>
        <el-form-item label="题目内容">
          <el-input v-model="formData.content" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="选项A">
          <el-input v-model="formData.optionA" />
        </el-form-item>
        <el-form-item label="选项B">
          <el-input v-model="formData.optionB" />
        </el-form-item>
        <el-form-item label="选项C">
          <el-input v-model="formData.optionC" />
        </el-form-item>
        <el-form-item label="选项D">
          <el-input v-model="formData.optionD" />
        </el-form-item>
        <el-form-item label="答案">
          <el-select v-if="formData.questionType === 1" v-model="formData.answer" placeholder="请选择答案">
            <el-option label="A" value="A" />
            <el-option label="B" value="B" />
            <el-option label="C" value="C" />
            <el-option label="D" value="D" />
          </el-select>
          <el-input v-else v-model="formData.answer" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="解析">
          <el-input v-model="formData.analysis" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="editDialogVisible"
      title="编辑题目"
      width="60%">
      <el-form :model="editFormData" label-width="100px">
        <el-form-item label="题目标题">
          <el-input v-model="editFormData.title" />
        </el-form-item>
        <el-form-item label="题目内容">
          <el-input v-model="editFormData.content" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="选项A">
          <el-input v-model="editFormData.optionA" />
        </el-form-item>
        <el-form-item label="选项B">
          <el-input v-model="editFormData.optionB" />
        </el-form-item>
        <el-form-item label="选项C">
          <el-input v-model="editFormData.optionC" />
        </el-form-item>
        <el-form-item label="选项D">
          <el-input v-model="editFormData.optionD" />
        </el-form-item>
        <el-form-item label="答案">
          <el-select v-if="editFormData.questionType === 1" v-model="editFormData.answer" placeholder="请选择答案">
            <el-option label="A" value="A" />
            <el-option label="B" value="B" />
            <el-option label="C" value="C" />
            <el-option label="D" value="D" />
          </el-select>
          <el-input v-else v-model="editFormData.answer" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="解析">
          <el-input v-model="editFormData.analysis" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdate">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.examination-question-container {
  padding: 20px;

  .filter-section {
    margin-bottom: 20px;
    display: flex;
    gap: 20px;
    align-items: center;
  }

  .operation-section {
    margin-bottom: 20px;
  }
}
</style>
